package com.csu.bailan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.bailan.domain.Order;
import com.csu.bailan.domain.OrderItem;
import com.csu.bailan.domain.SKU;
import com.csu.bailan.dto.CreateOrderDTO;
import com.csu.bailan.persistence.mapper.OrderItemMapper;
import com.csu.bailan.persistence.mapper.OrderMapper;
import com.csu.bailan.persistence.mapper.SKUMapper;
import com.csu.bailan.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static java.lang.Math.max;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private SKUMapper skuMapper;

    @Override
    public List<Order> getOrderByUserID(String userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return orderMapper.selectList(wrapper);
    }

    @Override
    public Order getOrderByOrderID(String orderId) {
        return orderMapper.selectById(orderId);
    }

    @Override
    public List<OrderItem> getOIByOrderId(String orderId) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        return orderItemMapper.selectList(wrapper);
    }

    @Override
    public boolean createOrder(CreateOrderDTO createOrderDTO, String userId) {
        //sku与对应购买数量的键值对
        Map<String,Integer> items = createOrderDTO.getItems();
        //订单物品列表
        List<OrderItem> orderItems = new ArrayList<>();
        //订单总额计数
        Double totalPrice = 0.;
        //遍历键值对，得到所有订单物品
        for (Map.Entry item : items.entrySet()) {
            //根据skuid找到商品
            SKU sku = skuMapper.selectById((String) item.getKey());
            //商品不存在或非售卖状态则生成订单失败
            if(sku == null || sku.getSkuStatus() != 1) {
                return false;
            }

            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(sku.getSkuId());
            orderItem.setAmount((Integer) item.getValue());
            orderItem.setSale(sku.getPrice());
            //加入列表
            orderItems.add(orderItem);
            //增加订单总额
            totalPrice += sku.getPrice() * (Integer) item.getValue();

            //System.out.println("key = " + item.getKey() + ", value = " + item.getValue());
        }

        //创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);
        //实付款价格为总额减去优惠额
        order.setToPay(max(totalPrice - createOrderDTO.getDiscount(),0));
        order.setAddrId(createOrderDTO.getAddrId());
        order.setComment(createOrderDTO.getComment());
        order.setCreateTime(new Date());
        //暂定1为待付款状态
        order.setOrderStatus(1);

        //订单写入数据库返回order_id
        int num1 = orderMapper.insert(order);
        if (num1 <= 0) {
            return false;
        }
        //遍历列表，订单物品设置order_id后写入数据库
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getOrderId());
            int num2 = orderItemMapper.insert(orderItem);
            if(num2 <= 0) {
                return false;
            }

        }
        return true;
    }

    @Override
    public boolean deleteOrderByOrderId(String orderId) {
        return false;
    }
}
